package com.study.mirrorforest.main.model.entries.service.Impl;

import com.study.mirrorforest.main.common.response.R;
import com.study.mirrorforest.main.common.utils.qwen.QwenApiUtil;
import com.study.mirrorforest.main.common.utils.qwen.QwenRequestDTO;
import com.study.mirrorforest.main.common.utils.qwen.QwenResponseDTO;
import com.study.mirrorforest.main.model.entries.dto.CreateEntriesDTO;
import com.study.mirrorforest.main.model.entries.dto.EntriesDTO;
import com.study.mirrorforest.main.model.entries.mapper.EntriesMapper;
import com.study.mirrorforest.main.model.entries.service.EntriesService;
import com.study.mirrorforest.main.model.summaries.dto.SummariesDTO;
import com.study.mirrorforest.main.model.summaries.mapper.SummariesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class EntriesServiceImpl implements EntriesService {

    @Autowired
    private EntriesMapper entriesMapper;

    @Autowired
    private QwenApiUtil qwenApiUtil;

    @Autowired
    private SummariesMapper summariesMapper;

    @Override
    public R CreateEntry(CreateEntriesDTO entry) {

        EntriesDTO newEntry = new EntriesDTO();

        newEntry.setTitle(entry.getTitle());
        newEntry.setContent(entry.getContent());
        newEntry.setMood(entry.getMood());
        newEntry.setVisibility("public");
        newEntry.setDate(entry.getDate());
        newEntry.setOwnerId(entry.getOwner_id());
        newEntry.setCreatedAt(new Date());
        newEntry.setUpdatedAt(new Date());
        entriesMapper.insert(newEntry);

        QwenRequestDTO qwenRequestDTO = new QwenRequestDTO();
        String sysPrompt = "你是专业的日记分析助手，核心职责是基于用户提供的单篇日记内容，进行客观、共情、有价值的分析。请严格遵循以下要求执行：\n" +
                "角色定位：保持中立且温暖的态度，不做主观评判，尊重日记中的个人情绪与隐私，所有分析仅基于文本本身，不进行过度联想。\n" +
                "分析维度（需全覆盖，不遗漏关键信息）：\n" +
                "情绪识别：提炼日记中最核心的 1-3 种情绪（如开心、焦虑、疲惫、期待等），并标注情绪对应的文本依据（简洁引用关键句）；\n" +
                "核心事件：梳理日记中记录的主要事件（按逻辑顺序简要概括，不添加额外细节）；\n" +
                "主题归纳：总结日记的核心主题（如工作压力、人际关系、自我成长、生活琐事等）；\n" +
                "潜在需求：挖掘用户可能未明确表达的潜在诉求（如需要倾诉、寻求解决方案、渴望认可等）；\n" +
                "正向引导（可选）：若日记包含负面情绪，提供 1-2 条温和、可行的小建议（不说教，聚焦情绪缓解或问题简化）；若为积极情绪，强化正向感受。\n" +
                "输出格式：分点清晰呈现，语言简洁易懂，避免专业术语，总长度控制在 300 字以内，让用户快速获取核心结论。\n" +
                "隐私原则：所有分析仅针对当前提供的日记内容，不存储、不关联其他信息，全程保护用户隐私。\n" +
                "请基于上述要求，对用户提供的日记进行全面且精炼的分析。";
        qwenRequestDTO.setSystemPrompt(sysPrompt);
        String prompt ="这是我今天的日志，你可以帮我分析一下吗？\n"
                +"日记的内容如下:\n" + entry.getContent()
                +"日记的标题是\n"+entry.getTitle()
                +"用户的情绪（[-3,3]中的整数）"+entry.getMood();
//        System.out.println("提示词"+prompt);
        qwenRequestDTO.setPrompt(prompt);
        try {
            QwenResponseDTO response =  qwenApiUtil.chat(prompt,sysPrompt);
            System.out.println("Qwen Response: " + response.getText());

            SummariesDTO summariesDTO = new SummariesDTO();
            summariesDTO.setEntryId(newEntry.getId());
            summariesDTO.setOwnerId(entry.getOwner_id());
            summariesDTO.setContent(response.getText());
            summariesDTO.setCreatedAt(new Date());
            summariesDTO.setUpdatedAt(new Date());
            summariesDTO.setType("Daily");
            summariesDTO.setTokensUsed(response.getTotalTokens());
            summariesDTO.setModel("qwen-flash");
            Date periodStart = new SimpleDateFormat("yyyy-MM-dd").parse(entry.getDate());
            summariesDTO.setPeriodStart(periodStart);
            summariesDTO.setPeriodEnd(periodStart);
            summariesMapper.insert(summariesDTO);
            return R.ok(200, "Entry created successfully");

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(500, "Failed to analyze entry content");
        }



    }
    @Override
    public R GetEntryList(Long userId,String title) {
        if(userId==null){
            return R.error(400,"User ID cannot be null");
        }
        List<EntriesDTO> entryList;
        if(title==null){
            entryList = entriesMapper.selectByOwnerId(userId);
        }
        else{
            entryList = entriesMapper.selectByTitle(userId,title);
        }
        System.out.println(entryList);
        HashMap<String,Object> result = new HashMap<>();
        result.put("list",entryList);
        result.put("total",entryList.size());
        return R.ok(200, "Entry list retrieved successfully",result);
    }


}
